package com.fstec.ks.master.dao.jdbc;

import java.util.Date;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.fstec.ks.master.dao.ServerInfoDao;
import com.fstec.ks.master.dao.jdbc.extractor.ServerInfoExtractor;
import com.fstec.ks.master.vo.ServerInfoVO;
import com.sinotn.id.SeqUUIDGenerator;
import com.sinotn.spring.jdbc.ParameterSetter;

public class DefaultServerInfoDao extends JdbcDaoSupport implements ServerInfoDao {
	private String schema;
	private String tableName="km_server_info";

	public void setSchema(String schema) {
		this.schema = schema;
	}

	@Override
	public ServerInfoVO select() {
		StringBuilder sb=new StringBuilder();
		sb.append("SELECT ").append(ServerInfoExtractor.getColumns());
		sb.append(" FROM ").append(this.schema).append(".").append(this.tableName);
		return this.getJdbcTemplate().query(sb.toString(), new ServerInfoExtractor());
	}

	@Override
	public void insert(ServerInfoVO serverInfoVo) {
		if(serverInfoVo.getId()==null){
			serverInfoVo.setId(SeqUUIDGenerator.genSequenceUUID());
		}
		if(serverInfoVo.getAuthTime()==null){
			serverInfoVo.setAuthTime(new Date());
		}
		StringBuilder sb=new StringBuilder();
		sb.append("INSERT INTO ").append(this.schema).append(".").append(this.tableName);
		sb.append(" (").append(ServerInfoExtractor.getColumns()).append(") VALUES (?,?,?,?)");
		//id,ip_addr,auth_num,auth_time
		ParameterSetter ps=new ParameterSetter(4);
		ps.set(serverInfoVo.getId());
		ps.set(serverInfoVo.getIpAddr());
		ps.set(serverInfoVo.getAuthNum());
		ps.set(serverInfoVo.getAuthTime().getTime());
		this.getJdbcTemplate().update(sb.toString(), ps);
	}

	@Override
	public int updateAuth(String id, String newAuth) {
		StringBuilder sb=new StringBuilder();
		sb.append("UPDATE ").append(this.schema).append(".").append(this.tableName);
		sb.append(" SET auth_num=?,auth_time=? WHERE id=?");
		ParameterSetter ps=new ParameterSetter(3);
		ps.set(newAuth);
		ps.set(System.currentTimeMillis());
		ps.set(id);
		return this.getJdbcTemplate().update(sb.toString(), ps);
	}

	@Override
	public int updateIpAddr(String id, String ipAddr) {
		StringBuilder sb=new StringBuilder();
		sb.append("UPDATE ").append(this.schema).append(".").append(this.tableName);
		sb.append(" SET ip_addr=? WHERE id=?");
		ParameterSetter ps=new ParameterSetter(2);
		ps.set(ipAddr);
		ps.set(id);
		return this.getJdbcTemplate().update(sb.toString(), ps);
	}
}
